<template>
  <div>
    <van-checkbox v-model="$store.state.quanxuan">全选</van-checkbox>
    <van-card
      v-for="(item,index) in shoparr"
      :key="index"
      :num="item.num"
      :price="item.price"
      desc="这个一个商品"
      :title="item.tit"
      :thumb="item.img"
    >
      <template #footer>
        <van-checkbox v-model="item.checked" style="width: 20px" @click="aaa(index)"></van-checkbox>
        <van-button size="mini" @click="subtract(item.id)">-</van-button>
        <van-button size="mini" @click="addnum(item.id)">+</van-button>
      </template>
    </van-card>
    <van-submit-bar :price="totalPrice * 100" button-text="提交订单">
      <template #tip>
        您购买的商品的总个数为
        <span>{{totalnum}}个</span>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      totalPrice: 0,
      totalnum:0
    };
  },
  computed: {
    ...mapState(["shoparr", "quanxuan"]),
  },
  watch: {
    // 侦听器
    shoparr: {
      // 监听shoparr的改变，shoparr一发生改变就执行
      handler(newval, oldval) {
        let newflag = this.shoparr.every((item) => item.checked);
        console.log(newflag);
        this.cheekitem(newflag);
        this.totalPrice = this.shoparr.reduce((a, b) => {
          if (b.checked) {
            return a + b.price * b.num;
          }
          return a;
        }, 0);
        this.totalnum = this.shoparr.reduce((a, b) => {
          if (b.checked) {
            return a + b.num;
          }
          return a;
        }, 0);
      },
      immediate: true, // 立即开始监听
      deep: true, // 开启深度监听
    },
    quanxuan: {
      handler() {
        console.log(this.quanxuan);
        this.changeallfn(this.quanxuan);
      },
      immediate: true, // 立即开始监听
      deep: true, // 开启深度监听
    },
   
  },
  methods: {
    ...mapMutations([
      "addNum",
      "subTract",
      "changeallfn",
      "fanxuan",
      "cheekitem",
    ]),
    addnum(id) {
      // 加法
      this.addNum(id);
    },
    subtract(id) {
      // 减法
      this.subTract(id);
    },
    changefn() {
      // 全选的事件
      this.changeallfn();
    },
     aaa (index) {
      let flag = this.shoparr.every((item)=>item.checked)
      console.log(flag,"falg",index,111);
    }
    //   cheekitem () { // 单选以及反选
    // //   console.log(1);
    //     this.fanxuan()
    //   }
  },
};
</script>

<style scoped>
.van-card__footer {
  display: flex;
  justify-content: flex-end;
}
</style>